from django.db import models
from django.utils import timezone


class Category(models.Model):
    """科目分类模型"""
    name = models.CharField(max_length=50, verbose_name="科目名称", unique=True)
    color = models.CharField(max_length=7, default="#007bff", verbose_name="标签颜色")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    
    class Meta:
        verbose_name = "科目分类"
        verbose_name_plural = "科目分类"
        ordering = ['name']
    
    def __str__(self):
        return self.name


class TodoItem(models.Model):
    """待办事项模型"""
    PRIORITY_CHOICES = [
        ('low', '低'),
        ('medium', '中'),
        ('high', '高'),
        ('urgent', '紧急'),
    ]
    
    title = models.CharField(max_length=200, verbose_name="标题")
    description = models.TextField(blank=True, verbose_name="详细描述")
    category = models.ForeignKey(
        Category, 
        on_delete=models.SET_NULL, 
        null=True, 
        blank=True,
        related_name='todos',
        verbose_name="科目分类"
    )
    priority = models.CharField(
        max_length=10, 
        choices=PRIORITY_CHOICES, 
        default='medium',
        verbose_name="优先级"
    )
    due_date = models.DateTimeField(null=True, blank=True, verbose_name="截止日期")
    is_completed = models.BooleanField(default=False, verbose_name="是否完成")
    completed_at = models.DateTimeField(null=True, blank=True, verbose_name="完成时间")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    
    class Meta:
        verbose_name = "待办事项"
        verbose_name_plural = "待办事项"
        ordering = ['-priority', 'due_date', '-created_at']
    
    def __str__(self):
        return self.title
    
    def save(self, *args, **kwargs):
        """保存时自动设置完成时间"""
        if self.is_completed and not self.completed_at:
            self.completed_at = timezone.now()
        elif not self.is_completed:
            self.completed_at = None
        super().save(*args, **kwargs)
    
    @property
    def is_overdue(self):
        """判断是否已过期"""
        if self.due_date and not self.is_completed:
            return timezone.now() > self.due_date
        return False
    
    @property
    def priority_display(self):
        """获取优先级显示文本"""
        return dict(self.PRIORITY_CHOICES).get(self.priority, '中')
